<?php

yii::import('pictures.models.File');

class SaveFileBehavior extends CActiveRecordBehavior
{

    public $field_name;
    public $savelocation;
    public $connection;
    public $postname;
    public $entity;
    public $oneImage = false;

    protected function normilizeFile($filePost)
    {
        if (is_array($filePost))
        {
            $i = 0;
            $result = array();
            foreach ($filePost as $id => $file)
            {
                if (substr($id, 0, 2) == 'id')
                {
                    $result[$id] = $file;
                    continue;
                }

                if (isset($file['file']))
                    $result[$i] = array('file' => $file['file']);
                else
                {
                    $result[$i++]['desc'] = $file['desc'];
                }
            }
            return $result;
        }
        throw new Exception('Array expected, but something else given');
    }

    /**
     *  Event handler to save all attached files
     */
    public function afterSave($event)
    {
        //print 'SAVE-FILE-BEHAVIOR:<br>';
       
        if (isset($_POST['File']))
        {
          	// if load ajax files          	
          	if ($_POST['File'][0]!='') {
								foreach ($_POST['File'] as $key => $file) {
									$f = File::model()->findbyPK($file['file']);
									
									if ($key==0) $f->default = 1;
									else  $f->default = 0;		
									
									$newPath = str_replace('temp',$this->savelocation,$f->file);
									
									if (!file_exists(yii::getPathOfAlias('webroot') . '/' . $newPath)) {
										copy(yii::getPathOfAlias('webroot') . '/' . $f->file,yii::getPathOfAlias('webroot') . '/' . $newPath);
										@unlink(yii::getPathOfAlias('webroot').'/' . $f->file);
									}
									// Если не надо загружать много файлов а только один, и если он	есть у модели то его заменять							
									if ($this->oneImage)	{
										$fOne = File::model()->find('entity="'.$this->entity.'" and entity_pk='.$this->owner->id);
										
										if ($fOne!=null) {										
											
											$fOne->file = $newPath;						
											if ($fOne->save()) { 
												if ($f->entity=='temp')  {														
													@unlink(yii::getPathOfAlias('webroot').'/' . $f->file);
													$f->delete(); 
												}
											} else echo 'not save';
											
										} else {
											$f->savelocation = $this->savelocation;
											$f->entity = $this->entity;
											$f->entity_pk = $this->owner->id;
											
											$f->num = $key;
											$f->file = $newPath;						
											$f->save();
										}
									}	else {										
										$f->savelocation = $this->savelocation;
										$f->entity = $this->entity;
										$f->entity_pk = $this->owner->id;
										
										$f->num = $key;
										$f->file = $newPath;						
										$f->save();
									}
											
									
									
									
									
									
								}
								unset($_SESSION['last_files']);
								return true;
          	}
         
            // normilize array
            
            $_POST['File'] = $this->normilizeFile($_POST['File']);
            
            //print 'normilized#' . 
            
            /* 
            foreach ($_POST['File'] as $fid => $file)
            {
                //print 'start#'.$fid.'<br>';
                // Modify old, or create new
                 
                if (substr($fid, 0, 2) == 'id')
                {
                    $f = File::model()->findbyPK(substr($fid, 2));
                    if (trim($file['file']) == '')
                        unset($file['file']);
                }
                else  {
                    $f = new File;
                    
                }
                //print 'exists#'.(!$f->isNewRecord?'yes':'no').'<br>';

                $f->savelocation = $this->savelocation;
                $f->attributes = $file;
                $f->entity = $this->entity;
                $f->entity_pk = $this->owner->id;
                $upfile = CUploadedFile::getInstanceByName('File[' . $fid . '][file]');
                
                //print 'file#'.//print_r($file,true).'<br>';
                // creating UploadFile instance and decide to save or no
                //$upfile = CUploadedFile::getInstanceByName('File[' . $fid . '][file]');
                 
                if ($upfile)
                {
             
                    //print 'upload is valid<br>';
                    // removing old picture file if exists
                    if (!$f->isNewRecord)
                    {
                        //print 'remove old picture#'.$f->id.'<br>';
                        $f->deleteFile($f->id);
                    }

                    $f->file = $upfile;
                    $fileName = md5(time() . uniqid()) . '.' . $upfile->extensionName;
                    //print 'filename#'.$fileName.'<br>';
                    //print 'file field#'.$f->file.'<br>';
                    $path = yii::getPathOfAlias('webroot.images.' . $this->savelocation.'/');
                        if(!file_exists($path)){
                            mkdir($path);
                        }
                    $res = $upfile->saveAs(yii::getPathOfAlias('webroot.images.' . $this->savelocation) . '/' . $fileName);
                        
                        // here is hack. cant solve for a moment
                        $f->file = 'images/' . $this->savelocation . '/' . $fileName;
                }
                //if(file_exists(yii::getPathOfAlias('webroot') . '/' . $this->savelocation. '/' . $fileName))
                if ($f->file!='' && $f->save())
                {
                    //print 'saving success<br>';
                    //file was uploaded - save it
                    if ($upfile)
                    {

                        if(file_exists(yii::getPathOfAlias('webroot.images') . '/' . $this->savelocation. '/' . $fileName)){
                            
                         Yii::app()->ih
                        ->load(yii::getPathOfAlias('webroot.images') . '/' . $this->savelocation. '/' . $fileName)
                        ->watermark(yii::getPathOfAlias('webroot') . '/images/watermark/logo.png', 10, 20, CImageHandler::CORNER_CENTER)
                        ->save(yii::getPathOfAlias('webroot.images') . '/' . $this->savelocation. '/' . $fileName);
                        }
                    }
                      
                     
                                   
                    // connection routines
                    //AbstractFilesConnector::SetConnection($this->entity,$this->owner->id, $f->id);
                }
               // else
               // {
                //    print_r($f->getErrors());
               //     throw new Exception('Cant save file');
               // }
            }
            */
           
            //exit('stop!<br>');
        }
        return true;
    }

    public function getFiles()
    {
    		$query ='';
        if (isset($_SESSION['last_files'])) {
        	$ids= implode(',',$_SESSION['last_files']);
        	$query = ' or id in ('.$ids.')';
				}
        return File::model()->findAll('(entity=:entity AND entity_pk=:pid)'.$query, array(':entity' => $this->entity, ':pid' => $this->owner->id));
    }
    
    public function getFilesSession()
    {
        if (isset($_SESSION['last_files'])) {
					$ids= implode(',',$_SESSION['last_files']);
					return File::model()->findAll('id in ('.$ids.')');
        } else {
					return false;
        }
        
    }

    public function beforeDelete($event)
    {
        $fname = $this->field_name;
        $files = $this->getFiles();

        foreach ($files as $file)
        {
            $file->delete();
        }

        return true;
    }

}

?>